package com.project.core.handle;

import com.project.core.anno.ScoreLog;
import com.project.core.constant.ScoreConstant;
import com.project.core.entity.ScoreLogEntity;
import com.project.core.util.CommonUtil;
import com.project.core.util.ScoreContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author mengxj
 */
@Aspect
@Component
public class ScoreLogHandle {

    @Pointcut("@annotation(com.project.core.anno.ScoreLog)")
    private void cut(){
    }

    @Around("cut()")
    public Object checkParam(ProceedingJoinPoint point){
        Method targetMethod = ((MethodSignature)point.getSignature()).getMethod();
        Class<?> cls = point.getTarget().getClass();
        ScoreLog scoreLog = targetMethod.getAnnotation(ScoreLog.class);
        if(Objects.isNull(scoreLog)){
            scoreLog = cls.getAnnotation(ScoreLog.class);
        }
        String value = scoreLog.value();
        ScoreLogEntity logEntity = new ScoreLogEntity();
        logEntity.setClassName(cls.getCanonicalName());
        logEntity.setMethodName(targetMethod.getName());
        logEntity.setTitle(value);
        logEntity.setCreateTime(LocalDateTime.now());
        logEntity.setCreateBy(ScoreContext.currentUser().getId());
        try {
            Object obj = point.proceed();
            logEntity.setContent(ScoreConstant.DEFAULT_LOG_MESSAGE);
            this.handleLog(logEntity);
            return obj;
        }catch (Throwable e){
            String message = CommonUtil.getExceptionMessage(e);
            logEntity.setContent(message);
            this.handleLog(logEntity);
            CommonUtil.throwException("方法执行异常", e);
            return null;
        }
    }

    private void handleLog(ScoreLogEntity logEntity){
        System.out.println(logEntity);
    }
}
